/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.Comments;
import edu.cmu.fithub.db.bean.Posts;
import edu.cmu.fithub.db.bean.User;
import edu.cmu.fithub.formbeans.LoginForm;
import edu.cmu.fithub.formbeans.RegisterForm;

public class DeleteCommentAction extends Action {

	private FormBeanFactory<LoginForm> formFactory = FormBeanFactory
			.getInstance(LoginForm.class);

	public DeleteCommentAction() {
	}

	public String getName() {
		return "deleteComments.do";
	}

	public String perform(HttpServletRequest request) {

		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		String commentId = request.getParameter("commentId");
		User user = (User) request.getSession().getAttribute("user");
		Session dbSession = DBHelper.getSessionFactory().openSession();
		try {
			List<Comments> commentList = dbSession.createCriteria(Comments.class)
					.add(Restrictions.eq("user.userId", user.getUserId()))
					.add(Restrictions.eq("commentId", Integer.parseInt(commentId)))
					.list();
			if (commentList.size() != 0) {
				// delete post from the tables along-with all comments made on
				// it.
				dbSession.beginTransaction();
				dbSession.delete(commentList.get(0));
				dbSession.getTransaction().commit();
			} else {
				errors.add("No such comment exists!!!");
				return "error.jsp";
			}
		} catch (NumberFormatException e) {
			errors.add(e.toString());
			return "error.jsp";
		}
		return "redirectToHome.jsp";
	}
}
